(function () {
  'use strict';
  var dictData = {
    status: {
      '0': '已使用',
      '1': '未使用'
    },
    cityId: {},
    plan: {},
    coupon_type: {},
    mutualType: {
      '1': '不互斥',
      '2': '全部互斥',
      '3': '指定互斥'
    },
    push: {}
  };

  var pushData = {};

  // 当前营销方案列表
  var planList = [];
  // 当前选择的营销方案列表
  var curPlanList = [];

  // 今天的最后一秒
  var curLastSecond = util.getTime(util.getDate(true) + ' 23:59:59');

  var $curPlanList = $('#selected-plan-list');

  main(function () {

    var $tablePush = $('#table-push');
    util.jqGrid($tablePush, {
      url: ajaxURL.COUPON + '/coupon/v1/planPush/getList',
      // 临时变更
      prmNames: {
        rows: 'pageNum',
        page: 'pageSize'
      },
      mtype: 'GET',
      autowidth: true,
      height: $(window).height() - 480,
      multiselect: true,
      // multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        { name: 'userId', key: true, hidden: true },
        { label: '用户名', name: 'userName', width: 120 },
        { label: '用户电话', name: 'userPhone', width: 100 },

        { label: '拉新数', name: 'newNumber', width: 60 },
        { label: '总里程(km)', name: 'totalMileage', width: 80, formatter: function (v) {
          return v ? +(v / 1000).toFixed(2) : 0;
        } },
        {
          label: '当月里程(km)', name: 'monthlyMileage', width: 80, formatter: function (v) {
            return v ? +(v / 1000).toFixed(2) : 0;
          } },
        { label: '状态', name: 'state', width: 50, hidden: true },
        {
          label: '注册时间', name: 'regDate', width: 110, formatter: function (v, o, r) {
            return util.dateFormat(v);
          }
        }
      ],
      pager: '#pager-push',
      loadComplete: function (res) {
        pushData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            pushData[item.kid] = item;
          });
        }
      }
    });

    function searchListTable() {
      var data = util.formData('#form-search');
      var searchData = {
        userName: data.userName,
        userPhone: data.userPhone,
        regStartDate: '',
        regEndDate: ''
      };
      if (data.startDate) {
        var temp = data.startDate.split('至');
        searchData.regStartDate = util.getTime($.trim(temp[0]) + ' 00:00:00');
        searchData.regEndDate = util.getTime($.trim(temp[1]) + ' 23:59:59');
      }
      util.searchGrid($tablePush, searchData);
    }

    $('#btn-search').click(searchListTable).click();

    // ---------------------------------弹出框 --------------------
    var planData = {};

    var $tablePlan = $('#viewBoxDiv');

    util.jqGrid($tablePlan, {
      url: ajaxURL.COUPON + '/coupon/v1/plan/queryWithPage',
      mtype: 'POST',
      height: 300,
      width: 960,
      multiselect: true,
      shrinkToFit: true,
      colModel: [
        { label: '序号', name: 'kid', key: true, width: 50, fixed: true
        },
        { label: '方案名称', name: 'planName' },
        { label: '方案编号', name: 'planCode' },
        { label: '合作渠道', name: 'cooperationChannel' },
        { label: '邀请码', name: 'invitCode', width: 100 },
        {
          label: '互斥方案', name: 'mutualType', width: 100, formatter: function (v, o, r) {
            return dictData.mutualType[v] || '';
          }
        },
        { label: '领取上限', name: 'receiveLimt', width: 100 },
        {
          label: '有效期', name: 'valid_date', width: 220, formatter: function (v, o, r) {
            var ret = util.getDate(r.validityStartTime) + ' 至 ' + util.getDate(r.validityEndTime);
            if (curLastSecond > r.validityEndTime) {
              ret += ' (<span class="text-danger">已过期</span>)';
            }
            return ret;
          }
        },
        {
          label: '备注', name: 'remark', width: 100
        }
      ],
      loadComplete: function (res) {
        planData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            planData[item.kid] = item;
            dictData.plan[item.kid] = item.planName;
          });
        }

      },
      gridComplete: function () {
        $curPlanList.find('.plan-item').each(function () {
          var $this = $(this);
          var id = $this.attr('id');
          $tablePlan.find('tr#' + id).find('input:checkbox').attr('disabled', true).prop('checked', false);
        });
      },
      pager: '#pager-plan'
    }, true);

    function searchPlanTable() {

      var data = util.formData('#form-search');
      util.searchGrid($tablePlan, data);
    }

    $('#btn-search2').click(searchPlanTable);

    // 点击选择弹出模态框
    $('#btn-select').click(function () {
      searchPlanTable();
      $('.optionBox').html('');
      var textShowContent = '';
      util.layerOpen2({
        title: '营销方案选择',
        content: $('#layer-plan'),
        area: ['1000px', ''],
        btn: ['确定', '取消'],
        yes: function (index) {
          var $list = $('.textShow');

          if ($('.textShow').length < 1) {
            return util.tip.warn('请先选择营销方案');
          }
          $.each($('.textShow'), function (index, item) {
            var that = $(this);
            textShowContent = '<div class="plan-item" data-id=' + that.prop('id') + '>' + that.text().split('X')[0] + '<span class="close plan-del" data-id=' + that.prop('id') + '>&times</span></div>';
            $curPlanList.append(textShowContent);
          });

          layer.close(index);
        }
      });
    });

    // 生成选择的营销方案列表
    function genPlanHtml(list) {
      var ret = '';
      $.each(list, function (_, item) {

      });
    }

    // 删除营销方案
    $('.content-wrapper').on('click', '.plan-del', function () {
      var $this = $(this);
      var $parent = $this.parent();
      var kid = $parent.data('kid');
      layer.confirm('确定删除该方案？', function (index) {
        $parent.remove();
        var curList = $parent.parent().attr('id') === 'cur-plan' ? curPlanList : planList;
        $.each(curList, function (_, item) {
          if (item.kid === kid) {
            curList.splice(_, 1);
            return false;
          }
        });
        layer.close(index);
      });
    });

    // 用户点击添加多项
    $('.confirmS').click(function () {
      console.log(planData);
      var textShowContent = '';
      var arr = [];
      var comfirmState = false;
      var checkedState = true;
      $.each($tablePlan.find(':checkbox'), function (index, item) {
        var that = $(this);
        var valueText = '';

        if (that.prop('checked')) {
          comfirmState = true;
          $.each(planData, function (index, item2) {
            if (that.parent().parent().prop('id') == item2.kid) {
              valueText = item2.cooperationChannel;
            }
          });
          textShowContent += '<div class="textShow"  id=' + that.parent().parent().prop('id') + '>' + valueText + '<span class="textColor" id=' + that.parent().parent().prop('id') + '>X</span></div>';
          if ($('.textShow').length != 0) {
            $.each($('.textShow'), function (index, item) {
              var _id = $(this).prop('id');
              if (that.parent().parent().prop('id') == _id) {
                checkedState = false;
              }
            });
          }
        }

      });
      if (checkedState) {
        $('.optionBox').append(textShowContent);
      }

      // 删除已选中的方案
      $('.optionBox').find('.textColor').each(function () {
        var that = $(this);
        that.click(function () {
          that.parent().remove();
        });
      });
    });
    // 用户点击删除
    function delContentOption() {
      $('.content-box1').find('.spanContent').each(function () {
        var that = $(this);
        that.click(function () {
          $(this).parent().remove();

        });
      });
    }
    // 点击查询


    // 日期
    laydate.render({
      range: '至',
      elem: '#activeDate',
      type: 'date',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#activeDate').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 注册日期start
    laydate.render({
      range: '至',
      elem: '#startDate',
      type: 'date',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#startDate').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 推送操作
    $('#btn-push').click(function () {

      var data = {};
      data.planId = (function () {
        var ret = [];
        $('.finalComFirm').each(function () {
          var $this = $(this);
          ret.push($this.attr('id'));
        });
        return ret;
      })();

      data.planlist = {
        'createId': 1,
        'createTime': '2017-12-29T06:59:39.466Z',
        'kid': 1,
        'phone': 'string',
        'planId': 0,
        'status': 0,
        'userId': 0,
        'userName': 'string'
      };

      var users = util.getGridSelectedIds($tablePush);
      if (users.length === 0) {
        return util.tip.warn('请先选择要推送的用户');
      }
      if (data.planId.length === 0) {
        return util.tip.warn('请先选择要推送的营销方案');
      }

      data.plantList = [];

      users.forEach(function (item) {
        var curData = pushData[item];
        data.planList.push({
          'createId': curData.createId,
          'createTime': curData.createTime,
          'phone': curData.phone,
          'status': 0,
          'userId': item,
          'userName': curData.userName
        });
      });

      layer.confirm('确定向该用户推送已选中的优惠券？', {
        btn: ['确定', '再想一想']
      }, function () {
        util.post(ajaxURL.COUPON + '/coupon/v1/planPush/save', data, function (res) {
          util.tip.success('推送成功');
        });
      });
    });

    function getCouponData(data) {
      $('.finalComFirm').each(function () {
        var $this = $(this);
        data.push($this.attr('id'));
      });
    }

  });
})(window, jQuery);
